package home.study.xxy.bs.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import home.study.xxy.bs.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author xiaoxiangyu
 * @create 2022-05-18 19:16
 * @功能：
 */
@Slf4j
public class UserNamePwdFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        log.info("======== in TestFilter ========== ");
        //认证为post请求
        if (!request.getMethod().equals("POST")) {
            log.error("Authentication method not supported: " + request.getMethod());
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        //数据为json格式
        if (request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)) {
            try {
//                User user = new ObjectMapper().readValue(request.getInputStream(), User.class);
                Map<String,String> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
                String username = map.get(getUsernameParameter());
                String pwd = map.get(getPasswordParameter());
                log.info(username + " == " + pwd);

                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, pwd);
                setDetails(request,authenticationToken);
                return this.getAuthenticationManager().authenticate(authenticationToken);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //进行认证


        return super.attemptAuthentication(request, response);
    }
}
